package com.niiwoo.civet.account.service.local.refund.newRefund;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.niiwoo.civet.account.dao.entity.ProTransactionOrder;
import com.niiwoo.civet.trade.dto.common.BatchTransOrderDetailForAccountDTO;
import com.niiwoo.tripod.lanmao.component.LanMaoDirectService;
import com.niiwoo.tripod.lanmao.enums.PayCompanyEnum;
import com.niiwoo.tripod.lanmao.enums.PreprocessingBusinessTypeEnum;
import com.niiwoo.tripod.lanmao.enums.RechargeWayEnum;
import com.niiwoo.tripod.lanmao.request.AsyncTransactionRequest;
import com.niiwoo.tripod.lanmao.request.CancelPreTransactionRequest;
import com.niiwoo.tripod.lanmao.request.DirectRechargeRequest;
import com.niiwoo.tripod.lanmao.request.UserAutoPreTransactionRequest;
import com.niiwoo.tripod.lanmao.response.AsyncTransactionResponse;
import com.niiwoo.tripod.lanmao.response.DirectRechargeResponse;
import com.niiwoo.tripod.lanmao.response.LanMaoResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * Created by dell on 2018/1/31.
 * 懒猫还款基础服务
 */
@Slf4j
@Service
public class LanmaoRefundLocalService {
    @Autowired
    private LanMaoDirectService lanMaoDirectService;
    @Autowired
    private RefundQueryLocalService refundQueryLocalService;

    /**
     * 银行存管<批量交易(还款)>接口调用
     * @param batchTransOrderDetailForAccountDTO
     * @param batchRequestNo
     * @return
     */
    public AsyncTransactionResponse asyncTransaction(BatchTransOrderDetailForAccountDTO batchTransOrderDetailForAccountDTO, String batchRequestNo) {
        if(!refundQueryLocalService.checkRepaymentMoney(batchRequestNo)){
            log.error("应还金额与应收总额不相等,batchNo={}", batchRequestNo);
            return null;
        }
        AsyncTransactionRequest request = new AsyncTransactionRequest();
        request.setBatchNo(batchRequestNo);
        log.info("--repayment for lanmao start-----------");
        List<AsyncTransactionRequest.BizDetail> list = JSONObject.parseArray(JSON.toJSONString(batchTransOrderDetailForAccountDTO.getBatchTransOrderDetails()), AsyncTransactionRequest.BizDetail.class);
        request.setBizDetails(list);
        AsyncTransactionResponse resp = null;
        try {
            resp = lanMaoDirectService.asyncTransaction(request).get();
            log.info("--repayment for lanmao end-----------");
        } catch (Exception e) {
            log.error("repayment for lanmao.", e);
        }
        log.info("存管还款接口订单batchRequestNo={}返回json{}",batchRequestNo,JSON.toJSONString(resp));
        return resp;
    }

    /**
     * 银行存管<批量交易(还款)>接口调用
     * @param batchTransOrderDetailForAccountDTO
     * @param batchRequestNo
     * @return
     */
    public AsyncTransactionResponse asyncTransactionForRepeat(BatchTransOrderDetailForAccountDTO batchTransOrderDetailForAccountDTO, String batchRequestNo) {

        AsyncTransactionRequest request = new AsyncTransactionRequest();
        request.setBatchNo(batchRequestNo);
        log.info("--repayment for lanmao start-----------");
        List<AsyncTransactionRequest.BizDetail> list = JSONObject.parseArray(JSON.toJSONString(batchTransOrderDetailForAccountDTO.getBatchTransOrderDetails()), AsyncTransactionRequest.BizDetail.class);
        request.setBizDetails(list);
        AsyncTransactionResponse resp = null;
        try {
            resp = lanMaoDirectService.asyncTransaction(request).get();
            log.info("--repayment for lanmao end-----------");
        } catch (Exception e) {
            log.error("repayment for lanmao.", e);
        }
        log.info("存管还款接口订单batchRequestNo={}返回json{}",batchRequestNo,JSON.toJSONString(resp));
        return resp;
    }

    /**
     * 银行存管<还款授权预处理>调用
     *
     * @param requestNo
     * @param accountNo
     * @param amount
     * @param projectId
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    public LanMaoResponse userAutoPreTransaction(String requestNo, String accountNo, BigDecimal amount, Long projectId) {
        UserAutoPreTransactionRequest request = new UserAutoPreTransactionRequest();
        request.setRequestNo(requestNo);
        request.setPlatformUserNo(accountNo);
        request.setBizType(PreprocessingBusinessTypeEnum.REPAYMENT);
        request.setAmount(amount);
        request.setProjectNo(projectId.toString());
        LanMaoResponse resp = null;
        try {
            resp = lanMaoDirectService.userAutoPreTransaction(request).get();
        } catch (Exception e) {
            log.error("调用懒猫还款预处理--userAutoPreTransaction---", e);
        }
        log.info("预处理订单requestNo={}返回json{}",requestNo,JSON.toJSONString(resp));
        return resp;
    }

    /**
     * 代偿授权预处理调用
     *
     * @param requestNo
     * @param accountNo
     * @param amount
     * @param projectId
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    public LanMaoResponse userAutoPreTransactionForGuarantee(String requestNo, String accountNo, BigDecimal amount, Long projectId) {
        UserAutoPreTransactionRequest request = new UserAutoPreTransactionRequest();
        request.setRequestNo(requestNo);
        request.setPlatformUserNo(accountNo);
        request.setBizType(PreprocessingBusinessTypeEnum.COMPENSATORY);
        request.setAmount(amount);
        request.setProjectNo(projectId.toString());
        LanMaoResponse resp = null;
        try {
            resp = lanMaoDirectService.userAutoPreTransaction(request).get();
        } catch (Exception e) {
            log.error("调用懒猫还款预处理--userAutoPreTransaction---", e);
        }
        log.info("预处理订单requestNo={}返回json{}",requestNo,JSON.toJSONString(resp));
        return resp;
    }

    /**
     * 取消预处理
     * @param proTransactionOrder 原订单
     * @return
     */
    public LanMaoResponse cancelProTransaction(ProTransactionOrder proTransactionOrder){
        CancelPreTransactionRequest request = new CancelPreTransactionRequest();
        request.setAmount(proTransactionOrder.getAmount());
        request.setPreTransactionNo(proTransactionOrder.getRequestNo());
        request.setRequestNo("unfreeze-"+proTransactionOrder.getRequestNo());
        log.info("取消预处理requestNo={},原流水号={}",request.getRequestNo(),request.getPreTransactionNo());
        CompletableFuture<LanMaoResponse> future = lanMaoDirectService.cancelPreTransaction(request);
        LanMaoResponse response = null;
        try {
            response = future.get();
            log.info("rollbackProTransaction ,batchNo={},调用存管接口释放还款冻结金额，response={}",proTransactionOrder.getRequestNo(),JSON.toJSONString(response));
        } catch (InterruptedException | ExecutionException e) {
            log.error("rollbackProTransaction,,batchNo={},释放还款冻结金额异常",proTransactionOrder.getRequestNo(),e);
        }
        log.info("预处理订单取消requestNo={}返回json{}",proTransactionOrder.getRequestNo(),JSON.toJSONString(response));
        return response;

    }

    /**
     * 代扣接口
     * @param accountNo
     * @param requestNo
     * @param amount
     * @param payCompany
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    public DirectRechargeResponse directRecharge(String accountNo, String requestNo, BigDecimal amount, PayCompanyEnum payCompany) throws ExecutionException, InterruptedException {
        //调用存管接口进行代扣
        DirectRechargeRequest request = new DirectRechargeRequest();
        request.setPlatformUserNo(accountNo);
        request.setRequestNo(requestNo);
        request.setAmount(amount);
        request.setExpectPayCompany(payCompany);
        request.setRechargeWay(RechargeWayEnum.PROXY);
        DirectRechargeResponse directRechargeResponse = null;
        try {
            CompletableFuture<DirectRechargeResponse> future = lanMaoDirectService.directRecharge(request);
            directRechargeResponse = future.get();
        } catch (Exception e) {
            log.error("调用懒猫代扣接口--directRecharge--", e);
        }
        log.info("代扣接口已经发出请求requestNo={},withholdResponse={}",requestNo,JSON.toJSONString(directRechargeResponse));
        return directRechargeResponse;
    }

    /**
     * 代扣接口(自动冻结)
     * @param accountNo
     * @param requestNo
     * @param amount
     * @param payCompany
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    public DirectRechargeResponse directRechargeWithFreeze(String accountNo, String requestNo,String proxyPretransRequestNo,String proxyAppendRequestNo, BigDecimal amount, PayCompanyEnum payCompany) throws ExecutionException, InterruptedException {
        //调用存管接口进行代扣
        DirectRechargeRequest request = new DirectRechargeRequest();
        request.setPlatformUserNo(accountNo);
        request.setRequestNo(requestNo);
        request.setProxyPretransRequestNo(proxyPretransRequestNo);
        request.setProxyAppendRequestNo(proxyAppendRequestNo);
        request.setAmount(amount);
        request.setExpectPayCompany(payCompany);
        request.setRechargeWay(RechargeWayEnum.PROXY);
        DirectRechargeResponse directRechargeResponse = null;
        try {
             directRechargeResponse = lanMaoDirectService.directRecharge(request).get();
        } catch (Exception e) {
            log.error("调用懒猫代扣接口--directRecharge--", e);
        }
        log.info("代扣(冻结)接口响应结果requestNo={},json={}",requestNo,JSON.toJSONString(directRechargeResponse));
        return directRechargeResponse;
    }
}
